import { useState } from "react"
import { View, Text, Button, Picker } from "@tarojs/components"
import Taro from "@tarojs/taro"
import "./bazi.scss"

const heavenlyStems = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"]
const earthlyBranches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"]
const elements = ["木", "火", "土", "金", "水"]

const stemElements = {
  甲: "木",
  乙: "木",
  丙: "火",
  丁: "火",
  戊: "土",
  己: "土",
  庚: "金",
  辛: "金",
  壬: "水",
  癸: "水",
}

const branchElements = {
  子: "水",
  丑: "土",
  寅: "木",
  卯: "木",
  辰: "土",
  巳: "火",
  午: "火",
  未: "土",
  申: "金",
  酉: "金",
  戌: "土",
  亥: "水",
}

const elementColors = {
  木: "#4CAF50",
  火: "#F44336",
  土: "#FF9800",
  金: "#FFEB3B",
  水: "#2196F3",
}

const genders = ["男", "女"]

export default function BaziChart() {
  const [birthDate, setBirthDate] = useState("")
  const [birthTime, setBirthTime] = useState("")
  const [gender, setGender] = useState("男")
  const [chart, setChart] = useState(null)

  const calculateBazi = () => {
    if (!birthDate || !birthTime) {
      alert("请选择完整的出生信息")
      return
    }

    const date = new Date(`${birthDate}T${birthTime}:00`)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()

    const yearStem = heavenlyStems[(year - 4) % 10]
    const yearBranch = earthlyBranches[(year - 4) % 12]
    const monthStem = heavenlyStems[(year * 2 + month + 8) % 10]
    const monthBranch = earthlyBranches[(month + 2) % 12]
    const dayStem = heavenlyStems[Math.floor(date.getTime() / 86400000 + 49) % 10]
    const dayBranch = earthlyBranches[Math.floor(date.getTime() / 86400000 + 49) % 12]
    const hourStem = heavenlyStems[(Math.floor(hour / 2) + 9) % 10]
    const hourBranch = earthlyBranches[Math.floor(hour / 2) % 12]

    setChart({
      year: { stem: yearStem, branch: yearBranch },
      month: { stem: monthStem, branch: monthBranch },
      day: { stem: dayStem, branch: dayBranch },
      hour: { stem: hourStem, branch: hourBranch },
    })
  }

  const getElementCount = () => {
    if (!chart) return {}

    const counts = { 木: 0, 火: 0, 土: 0, 金: 0, 水: 0 }

    counts[stemElements[chart.year.stem]]++
    counts[stemElements[chart.month.stem]]++
    counts[stemElements[chart.day.stem]]++
    counts[stemElements[chart.hour.stem]]++

    counts[branchElements[chart.year.branch]]++
    counts[branchElements[chart.month.branch]]++
    counts[branchElements[chart.day.branch]]++
    counts[branchElements[chart.hour.branch]]++

    return counts
  }

  const elementCounts = getElementCount()

  return (
    <View className="bazi-chart">
      <View className="container">
        <View className="header">
          <Text className="title">八字排盘</Text>
          <Text className="subtitle">了解命理，把握人生</Text>
        </View>

        <View className="input-form card">
          <View className="form-item">
            <Text className="label">出生日期</Text>
            <Picker 
              mode="date" 
              onChange={(e) => setBirthDate(e.detail.value)}
            >
              <View className="input">{birthDate || '请选择日期'}</View>
            </Picker>
          </View>

          <View className="form-item">
            <Text className="label">出生时间</Text>
            <Picker 
              mode="time" 
              onChange={(e) => setBirthTime(e.detail.value)}
            >
              <View className="input">{birthTime || '请选择时间'}</View>
            </Picker>
          </View>

          <View className="form-item">
            <Text className="label">性别</Text>
            <Picker 
              mode="selector" 
              range={genders}
              onChange={(e) => setGender(genders[e.detail.value])}
            >
              <View className="input">{gender}</View>
            </Picker>
          </View>

          <Button className="calculate-button" onClick={calculateBazi}>
            排盘分析
          </Button>
        </View>

        {chart && (
          <View className="chart-result">
            <View className="bazi-pillars">
              <View className="pillar">
                <Text className="pillar-title">年柱</Text>
                <View className="pillar-content">
                  <Text className="stem">{chart.year.stem}</Text>
                  <Text className="branch">{chart.year.branch}</Text>
                </View>
                <Text className="element">
                  {stemElements[chart.year.stem]}
                  {branchElements[chart.year.branch]}
                </Text>
              </View>

              <View className="pillar">
                <Text className="pillar-title">月柱</Text>
                <View className="pillar-content">
                  <Text className="stem">{chart.month.stem}</Text>
                  <Text className="branch">{chart.month.branch}</Text>
                </View>
                <Text className="element">
                  {stemElements[chart.month.stem]}
                  {branchElements[chart.month.branch]}
                </Text>
              </View>

              <View className="pillar">
                <Text className="pillar-title">日柱</Text>
                <View className="pillar-content">
                  <Text className="stem">{chart.day.stem}</Text>
                  <Text className="branch">{chart.day.branch}</Text>
                </View>
                <Text className="element">
                  {stemElements[chart.day.stem]}
                  {branchElements[chart.day.branch]}
                </Text>
              </View>

              <View className="pillar">
                <Text className="pillar-title">时柱</Text>
                <View className="pillar-content">
                  <Text className="stem">{chart.hour.stem}</Text>
                  <Text className="branch">{chart.hour.branch}</Text>
                </View>
                <Text className="element">
                  {stemElements[chart.hour.stem]}
                  {branchElements[chart.hour.branch]}
                </Text>
              </View>
            </View>

            <View className="element-analysis card">
              <Text className="section-title">五行分析</Text>
              <View className="element-bars">
                {elements.map((element) => (
                  <View key={element} className="element-bar-container">
                    <Text className="element-name">{element}</Text>
                    <View className="element-bar-wrapper">
                      <View
                        className="element-bar"
                        style={{
                          width: `${elementCounts[element] * 12.5}%`,
                          backgroundColor: elementColors[element],
                        }}
                      />
                    </View>
                    <Text className="element-count">{elementCounts[element]}</Text>
                  </View>
                ))}
              </View>
            </View>

            <View className="life-analysis card">
              <Text className="section-title">命理分析</Text>
              <View className="analysis-card">
                <Text className="analysis-title">性格特点</Text>
                <Text className="analysis-content">
                  日主为{chart.day.stem}，{stemElements[chart.day.stem]}属性，性格
                  {stemElements[chart.day.stem] === "木"
                    ? "温和，富有同情心"
                    : stemElements[chart.day.stem] === "火"
                      ? "热情，富有感染力"
                      : stemElements[chart.day.stem] === "土"
                        ? "稳重，富有责任感"
                        : stemElements[chart.day.stem] === "金"
                          ? "果断，富有决策力"
                          : "灵活，富有智慧"}
                  。
                </Text>
              </View>
            </View>
          </View>
        )}
      </View>
    </View>
  )
}